from flask import Blueprint, render_template, request, redirect, url_for, flash
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
from database_operations import fetch_data

auth_app = Blueprint('auth', __name__, template_folder='templates')

# 设置 Flask-Login
login_manager = LoginManager()
login_manager.login_view = 'auth.login'

@login_manager.user_loader
def load_user(user_id):
    user = fetch_data('SELECT * FROM users WHERE id=%s', (user_id,))
    if user:
        return User(user_id)
    return None

class User(UserMixin):
    def __init__(self, id):
        self.id = id

@auth_app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        user = fetch_data('SELECT * FROM users WHERE username=%s AND password=%s', (username, password))
        if user:
            user_id = user[0]['id']
            user_obj = User(user_id)
            login_user(user_obj)
            flash
            return redirect(url_for('index'))
        flash('用户名或密码错误!')
    return render_template('login.html')

@auth_app.route('/logout')
@login_required
def logout():
    logout_user()
    flash
    return redirect(url_for('index'))

@auth_app.route('/profile')
@login_required
def profile():
    return f'Welcome {current_user.id}!'